#!/bin/bash



if [[ $# > 1 ]]; then
	wb=$2
elif [[ $# == 1 ]]; then
	wb=${HOME}/software
else
	exit 1
fi

backDir=${1}

if [[ $# > 2 ]]; then day=$3; else day=30; fi

oldFiles=`find $backDir -type f -mtime +30`
if [[ ${oldFiels} ]]; then rm $oldFiles ; fi

if [[ `find ${backDir} -name "*.tgz"` ]]; then
	lastFile=`ls -t ${backDir}/*.tgz | head -n 1`
else 
	lastFile=""
fi
if [[ $day < 32 ]]; then
	newFile=$(date +\%d_\%H_\%M).tgz
elif [[ $day < 367 ]]; then
	newFile=$(date +\%m_\%d).tgz
else
	newFile=$(date +\%Y_\%m).tgz
fi

expiredFiles=`find ${backDir} -mtime +${day}`
if [[ $expiredFiles ]]; then rm $expiredFiles; fi

cd $wb

files=$(for d in `find -maxdepth 1 -type d `; do if [[ -d ${d}/.git ]]; then cd $d; fs=`git ls-files -m`; for f in $fs; do echo $d/$f; done; cd ..; fi; done)
if [[ $files == "" ]]; then exit 1; fi
tar -zcvf ${newFile} $files
md51=`md5sum -b $newFile | cut -d " " -f 1`
if [[ $lastFile ]]; then
	md52=`md5sum -b $lastFile | cut -d " " -f 1`
	if [ "${md52}"  == "${md51}" ]; then 
		rm $newFile; 
	else 
		mv $newFile ${backDir}/$newFile
	fi
else
	mv $newFile ${backDir}/$newFile
fi

